package com.heima.test3;

public class SellTicket implements Runnable {
    private int tickets = 100;

    //在SellTicket类中重写run()方法实现卖票，代码步骤如下
    @Override
    public void run() {
        while (true) {
            if (sell())
                break;
        }
    }

    //同步方法 默认的锁是this
    public synchronized boolean sell() {
        if (tickets <= 0) {
            //判断ticket数量小于等于0，说明卖完了，结束循环
            return true;
        } else {
            try {
                Thread.sleep(100);//模拟卖票消耗100ms
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            tickets--;//卖票 导致数量-1
            System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + tickets + "张票");
            return false;
        }
    }
}